package com.lonely.framework.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.lonely.common.core.domain.auth.LoginUser;
import com.lonely.common.enums.DataScope;
import com.lonely.common.threadlocals.DataPermissionThreadLocal;
import com.lonely.common.utils.JsonUtil;
import com.lonely.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.HexValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.statement.select.PlainSelect;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author: 黄志标
 * @date: 2025/5/27 11:36
 * @description: 数据权限过滤处理器--拼接where条件
 */
@Slf4j
public class MyDataPermissionHandler {


    /**
     * 获取数据权限 SQL 片段
     *
     * @param plainSelect  查询对象
     * @param whereSegment 查询条件片段
     * @return JSqlParser 条件表达式
     */
    @SneakyThrows(Exception.class)
    public Expression getSqlSegment(PlainSelect plainSelect, String whereSegment) {

        log.info("开始进行权限过滤,mappedStatementId: {}", whereSegment);

        // 待执行 SQL Where 条件表达式
        Expression where = plainSelect.getWhere();
        LoginUser user = SecurityUtils.getLoginUser();

        // 如果是超级管理员，则不添加条件过滤
        if (user.getUser().isAdmin()) {
            return where;
        }


        DataScope scopeType = DataPermissionThreadLocal.getScope();

        switch (scopeType) {
            // 查看全部
            case ALL:
                return where;
            case FACTORY:
                // 查看本部门用户数据
                // 创建IN 表达式
                // 创建IN范围的元素集合
                Set<String> deptUserList = user.getFactoryDataPermissions();
                if (CollUtil.isEmpty(deptUserList)) {
                    log.debug("当前用户无工厂数据权限");
                    Expression hexValue = new HexValue(" 1 = 0 ");
                    return buildWhere(where, hexValue);
//                    if (where == null) {
//                        return new HexValue(" 1 = 0 ");
//                    }
//                    return new AndExpression(where, new HexValue(" 1 = 0 "));

                }
                // 把集合转变为JSQLParser需要的元素列表
                ItemsList factoryIds = new ExpressionList(deptUserList.stream().map(StringValue::new).collect(Collectors.toList()));
                InExpression inExpression = new InExpression(new HexValue(DataPermissionThreadLocal.getLeftExpress()), factoryIds);
                return buildWhere(where, inExpression);
//                if (where == null) {
//                    return inExpression;
//                }
//                return new AndExpression(where, inExpression);
            case ORDER_FACTORY:
                // 查看当前登录用户是否有订单
                String factoryPermissions = JsonUtil.toJsonString(Optional.ofNullable(SecurityUtils.getLoginUser().getFactoryDataPermissions()).orElse(new HashSet<>()).stream().map(Convert::toInt).collect(Collectors.toList()));
                String expressStr = "JSON_OVERLAPS (\n" +
                        "\t\t%s,\n" +
                        "\t'%s') ";
                String expressValue = String.format(expressStr,DataPermissionThreadLocal.getLeftExpress(),factoryPermissions);
                return buildWhere(where,new HexValue(expressValue));
//            case MYSELF:
            // 查看自己的数据
            //  = 表达式
//                        EqualsTo usesEqualsTo = new EqualsTo();
//                        usesEqualsTo.setLeftExpression(new Column(mainTableName + ".creator_code"));
//                        usesEqualsTo.setRightExpression(new StringValue(user.getUserCode()));
//                        return new AndExpression(where, usesEqualsTo);
//                return where;
            default:
                break;
        }

        //说明无权查看，
//        where = new HexValue(" 1 = 0 ");
        return where;
    }


    /**
     * 将数据过滤的条件追加到where中，如果没有where，则生成where，如果有where，则追加条件
     *
     * @param where
     * @param expression
     * @return
     */
    private Expression buildWhere(Expression where, Expression expression) {
        if (where == null) {
            return expression;
        }
        return new AndExpression(where, expression);
    }
}